using AuthService.Domain.Entities;
using AuthService.Domain.Enums;
using System.Text.Json;
using HttpMethod = AuthService.Domain.Enums.HttpMethod;

namespace AuthService.Infrastructure.DTOs;

/// <summary>
/// 动态API端点数据传输对象
/// 用于数据库映射和序列化
/// </summary>
public class DynamicApiEndpointDto
{
    public Guid Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string? Description { get; set; }
    public int Method { get; set; }
    public string PathTemplate { get; set; } = string.Empty;
    public string? TargetService { get; set; }
    public string? TargetUrl { get; set; }
    public bool IsEnabled { get; set; }
    public bool RequireAuthentication { get; set; }
    public string RequiredRoles { get; set; } = "[]";
    public string RequiredPermissions { get; set; } = "[]";
    public int? RateLimitPerMinute { get; set; }
    public int TimeoutSeconds { get; set; }
    public int RetryCount { get; set; }
    public int CacheSeconds { get; set; }
    public string Headers { get; set; } = "{}";
    public string QueryParameters { get; set; } = "{}";
    public string? RequestTransformation { get; set; }
    public string? ResponseTransformation { get; set; }
    public string Version { get; set; } = "1.0";
    public string Tags { get; set; } = "[]";
    public string? TenantId { get; set; }
    public int Priority { get; set; }
    public string? Metadata { get; set; }
    public DateTime? LastAccessedAt { get; set; }
    public long AccessCount { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public string? UpdatedBy { get; set; }
    public bool IsDeleted { get; set; }
    public DateTime? DeletedAt { get; set; }
    public string? DeletedBy { get; set; }

    /// <summary>
    /// 从实体转换为DTO
    /// </summary>
    /// <param name="endpoint">API端点实体</param>
    /// <returns>API端点DTO</returns>
    public static DynamicApiEndpointDto FromEntity(DynamicApiEndpoint endpoint)
    {
        return new DynamicApiEndpointDto
        {
            Id = endpoint.Id,
            Name = endpoint.Name,
            Description = endpoint.Description,
            Method = (int)endpoint.Method,
            PathTemplate = endpoint.PathTemplate,
            TargetService = endpoint.TargetService,
            TargetUrl = endpoint.TargetUrl,
            IsEnabled = endpoint.IsEnabled,
            RequireAuthentication = endpoint.RequireAuthentication,
            RequiredRoles = JsonSerializer.Serialize(endpoint.RequiredRoles),
            RequiredPermissions = JsonSerializer.Serialize(endpoint.RequiredPermissions),
            RateLimitPerMinute = endpoint.RateLimitPerMinute,
            TimeoutSeconds = endpoint.TimeoutSeconds,
            RetryCount = endpoint.RetryCount,
            CacheSeconds = endpoint.CacheSeconds,
            Headers = JsonSerializer.Serialize(endpoint.Headers),
            QueryParameters = JsonSerializer.Serialize(endpoint.QueryParameters),
            RequestTransformation = endpoint.RequestTransformation,
            ResponseTransformation = endpoint.ResponseTransformation,
            Version = endpoint.Version,
            Tags = JsonSerializer.Serialize(endpoint.Tags),
            TenantId = endpoint.TenantId,
            Priority = endpoint.Priority,
            Metadata = endpoint.Metadata,
            LastAccessedAt = endpoint.LastAccessedAt,
            AccessCount = endpoint.AccessCount,
            CreatedAt = endpoint.CreatedAt,
            UpdatedAt = endpoint.UpdatedAt,
            CreatedBy = endpoint.CreatedBy,
            UpdatedBy = endpoint.UpdatedBy,
            IsDeleted = endpoint.IsDeleted,
            DeletedAt = endpoint.DeletedAt,
            DeletedBy = endpoint.DeletedBy
        };
    }

    /// <summary>
    /// 转换为实体
    /// </summary>
    /// <returns>API端点实体</returns>
    public DynamicApiEndpoint ToEntity()
    {
        var endpoint = new DynamicApiEndpoint
        {
            Id = Id,
            Name = Name,
            Description = Description,
            Method = (HttpMethod)Method,
            PathTemplate = PathTemplate,
            TargetService = TargetService,
            TargetUrl = TargetUrl,
            IsEnabled = IsEnabled,
            RequireAuthentication = RequireAuthentication,
            RateLimitPerMinute = RateLimitPerMinute,
            TimeoutSeconds = TimeoutSeconds,
            RetryCount = RetryCount,
            CacheSeconds = CacheSeconds,
            RequestTransformation = RequestTransformation,
            ResponseTransformation = ResponseTransformation,
            Version = Version,
            TenantId = TenantId,
            Priority = Priority,
            Metadata = Metadata,
            LastAccessedAt = LastAccessedAt,
            AccessCount = AccessCount,
            CreatedAt = CreatedAt,
            UpdatedAt = UpdatedAt,
            CreatedBy = CreatedBy,
            UpdatedBy = UpdatedBy,
            IsDeleted = IsDeleted,
            DeletedAt = DeletedAt,
            DeletedBy = DeletedBy
        };

        // 反序列化集合属性
        try
        {
            endpoint.RequiredRoles = JsonSerializer.Deserialize<List<string>>(RequiredRoles) ?? new List<string>();
        }
        catch
        {
            endpoint.RequiredRoles = new List<string>();
        }

        try
        {
            endpoint.RequiredPermissions = JsonSerializer.Deserialize<List<string>>(RequiredPermissions) ?? new List<string>();
        }
        catch
        {
            endpoint.RequiredPermissions = new List<string>();
        }

        try
        {
            endpoint.Headers = JsonSerializer.Deserialize<Dictionary<string, string>>(Headers) ?? new Dictionary<string, string>();
        }
        catch
        {
            endpoint.Headers = new Dictionary<string, string>();
        }

        try
        {
            endpoint.QueryParameters = JsonSerializer.Deserialize<Dictionary<string, string>>(QueryParameters) ?? new Dictionary<string, string>();
        }
        catch
        {
            endpoint.QueryParameters = new Dictionary<string, string>();
        }

        try
        {
            endpoint.Tags = JsonSerializer.Deserialize<List<string>>(Tags) ?? new List<string>();
        }
        catch
        {
            endpoint.Tags = new List<string>();
        }

        return endpoint;
    }
}
